package Servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static MySql.MySqlStart.InitDatabaseCreate;
import static MySql.MysqlOperate.MySql_Operate;
import static MySql.MysqlSelect.MySQL_FindQQ;


public class RegisterServer extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            InitDatabaseCreate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        String QQ = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String tel = request.getParameter("tel");
        String sex = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = df.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Timestamp timeStamp = new Timestamp(new Date().getTime());
        if (MySQL_FindQQ(QQ) == true) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("<script language='javascript'>alert('该QQ已经被绑定了，请重新输入QQ');" +
                    "window.location.href='Register.jsp';</script>");
        }
        else {
            Object[] RegisterAddinfo = {
                    QQ,
                    password,
                    name,
                    tel,
                    Integer.parseInt(sex),
                    new java.sql.Date(date.getTime()),
                    timeStamp,
                    1
            };
            String RegisterSQL = "INSERT INTO PERSON VALUES(?,?,?,?,?,?,?,?);";
            try {
                MySql_Operate(RegisterSQL, RegisterAddinfo);
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script language='javascript'>alert('注册成功');" +
                        "window.location.href='Login.jsp';</script>");
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }
}
